using Cysharp.Threading.Tasks;
using Framework.Interface;
using Framework.Manager;
using Game.Hotfix;
using Game.System;
using Shared.App;
using Shared.UI;
using UnityEngine;

namespace Game.Logic.App
{
    public class App : MonoBehaviour
    {
        private ManagerFactory managerFactory = new();
        private SystemFactory sysFactory = new();
        
        private void Awake()
        {
            DontDestroyOnLoad(gameObject);
        }

        private async void Start()
        {
            EventsManager.Instance.Add<HotfixEndEvent>(HotfixEnd);
            EventsManager.Instance.Add<EnterGame>(RunGame);
            
            // 加载热更界面
            if (AppDefine.editorOpenHotfix)
            {
                Game.Hotfix.Hotfix hotfix = new Game.Hotfix.Hotfix();
                await hotfix.Start();
            }
            else
            {
                EventsManager.Instance.Broadcast(new HotfixEndEvent());
            }
        }
        
        // 热更结束
        private void HotfixEnd(IListener listener)
        {
            EventsManager.Instance.Broadcast(new HotfixConfirmEvent());
        }
        
        // 进入游戏
        private void RunGame(IListener listener)
        {
            AddGameScripts().ToCoroutine();
        }
        
        // 初始化游戏一些脚本
        private async UniTask AddGameScripts()
        {
            if (managerFactory != null)
            {
                managerFactory.RegisterManagers();
                await managerFactory.InitManagers(transform);
            }

            if (sysFactory != null)
            {
                sysFactory.RegisterSystems();
                await sysFactory.Initialize();
            }
            
            await UIManager.Instance.Active<Logic.Auth.Auth>(UIId.Auth);
        }
        
        private void OnDestroy()
        {
            EventsManager.Instance.Remove<HotfixEndEvent>(HotfixEnd);
            EventsManager.Instance.Remove<EnterGame>(RunGame);
            if (managerFactory != null)
            {
                managerFactory.Shutdown();
                managerFactory = null;
            }

            if (sysFactory != null)
            {
                sysFactory.Shutdown();
                sysFactory = null;
            }
        }
    }
}
